package com.zhugang.week13.linkedlist;

/**
 * @program algorithms
 * @description: removeNthFromEnd
 * @author: chanzhugang
 * @create: 2022/10/27 20:42
 */
public class RemoveNthFromEnd {

    /**
     * 19 删除链表的倒数第N个节点
     * https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
     * <p>
     * 和链表倒数第N个节点类似
     * https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
     *
     * @param head
     * @param n
     * @return
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // 先找到倒数第n个节点，然后找它的前置节点，prev.next = slow.next 删除slow节点
        // 快慢指针差的节点个数为n，快指针遍历结束，慢指针就是倒数第n个节点
        ListNode fast = head;
        int count = 0;
        while (fast != null) {
            count++;
            if (count == n) {
                break;
            }
            // 快指针先走了n步
            fast = fast.next;
        }
        if (fast == null) {
            // 链表长度不够n个，不用删除了
            return head;
        }

        ListNode slow = head;
        ListNode prev = null;
        while (fast.next != null) {
            // 找前驱节点
            prev = slow;
            slow = slow.next;
            fast = fast.next;
        }
        if (prev == null) {
            // 特殊处理：prev.next报错情况 头节点是倒数第n个节点
            head = head.next;
        } else {
            // slow此时是要删除的节点
            prev.next = slow.next;
        }
        return head;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}